package com.cby.code.encrypt;

import com.cby.code.util.CbyLogUtils;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * Description:RSA加密解密工具类
 *
 * @author 陈宝阳
 * @create 2019/5/23 09: 40
 */
public class RSAEncryptUtil {

  private static final String TAG = "RSAEncryptUtil";

  /**
   * RSA公钥加密(先数据RSA加密，再Base64加密)
   *
   * @param str 加密字符串
   * @param publicKey 公钥
   * @return 密文
   */
  public static String encryptByPublicKey(String str, String publicKey) {
    try {
      //base64编码的公钥
      byte[] decoded = Base64Utils.decodeToByte(publicKey);

      X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded);
      KeyFactory kf = KeyFactory.getInstance("RSA");
      PublicKey pubKey = kf.generatePublic(keySpec);

      //RSA加密
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      cipher.init(Cipher.ENCRYPT_MODE, pubKey);
      return Base64Utils.encode(cipher.doFinal(str.getBytes("UTF-8")));
    }catch (Exception e) {
      CbyLogUtils.i(TAG, "加密异常"+e.getMessage());
    }
    return null;
  }

  /**
   * RSA公钥解密(先数据Base64解密，在RSA解密)
   *
   * @param str 待解密数据
   * @param publicKey 密钥
   * @return byte[] 解密后的明文数据
   */
  public static String decryptByPublicKey(String str, String publicKey) {

    try {
      //64位解码加密后的字符串
      byte[] inputByte = Base64Utils.decodeToByte(str);
      //base64编码的公钥
      byte[] decoded = Base64Utils.decodeToByte(publicKey);

      X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded);
      KeyFactory kf = KeyFactory.getInstance("RSA");
      PublicKey keyPublic = kf.generatePublic(keySpec);

      // RSA数据解密
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      cipher.init(Cipher.DECRYPT_MODE, keyPublic);

      return new String(cipher.doFinal(inputByte));
    }catch (Exception e) {
      CbyLogUtils.i(TAG, "解密异常："+e.getMessage());
    }
    return null;
  }



}
